package com.cherry.example.network.udp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

//群聊的发送端
public class ChatSender extends Thread {

	@Override
	public void run() {
		try {
			//第一步：建立udp服务
			DatagramSocket socket  = new DatagramSocket();
			//第二步： 准备数据，把数据封装到数据包中。
			
			//创建键盘输入流
			BufferedReader keyReader = new BufferedReader(new InputStreamReader(System.in));
			String line = null;
			DatagramPacket packet= null;
			while((line=keyReader.readLine())!=null){
				//把数据封装到数据包中。
				packet = new DatagramPacket(line.getBytes(), line.getBytes().length, InetAddress.getLocalHost() , 9090);
				//把数据包发送
				socket.send(packet);
			}
			//关闭资源
			socket.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
